import Vue from "vue"; 
import Router from "vue-router"; 
// 动态导入组件 
const Home = () => import('@/components/Home'); 
const NewsList = () => import('@/components/NewsList'); 
const About = () => import('@/components/About'); 
const Sports = () => import('@/components/Sports'); 
const Technology = () => import('@/components/Technology.vue'); 
const NewsDetail = () => import('@/components/NewsDetail.vue'); 

const Login = () => import('@/components/Login.vue');

Vue.use(Router);

const router = new Router({
 routes: [
   {
     path: "/",
     name: "Home",
     component: Home,
   },
   {
     path: "/news-list",
     name: "NewsList",
     component: NewsList,
     children: [
       {
         path: "sports",
         name: "Sports",
         component: Sports,
       },
       {
         path: "technology",
         name: "Technology",
         component: Technology,
       },
       {
         path: "news-detail/:id",
         name: "NewsDetail",
         component: NewsDetail,
       },
     ],
   },
   {
     path: "/login",
     name: "Login",
     component: Login,
   },
   {
     path: "/about",
     name: "About",
     component: About,
   },
   {
     path: "/welcome",
     name: "Welcome",
     beforeEnter: (to, from, next) => {
       let isLogin = localStorage.getItem("isLogin") === "true";
       if (isLogin) {
         console.log("进入欢迎页，已经登录跳转首页！");
         next("/");
       } else {
         console.log("进入欢迎页，未登录跳转登录页！");
         next("/login");
       }
     },
   },
 ],
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
 let isLogin = localStorage.getItem("isLogin") === "true";
 if (to.path === "/login" || to.path === "/welcome" || isLogin) {
   next();
 } else {
   window.alert("未登录，请先登录！");
   next("/login");
 }
});

router.afterEach((to, from) => {
 console.log(`路由${from.path}切换${to.path}完成`);
});

export default router;